import { ref, reactive, watch, computed, nextTick } from 'vue'
export default function useFixed(props) {
  const TITLE_HEIGHT = 30
  const groupRef = ref(null)
  const listHeights = reactive([])
  const scrollY = ref(0)
  const currentIndex = ref(0)
  // 偏移量
  const distance = ref(0)
  // 获得滚动段的title
  const fixedTitle = computed(() => {
    if (scrollY.value < 0) {
      return
    }
    // 获取当前滚动到的区域dom
    const currentGroup = props.data[currentIndex.value]
    return currentGroup ? currentGroup.title : ''
  })
  const finedStyle = computed(() => {
    const distanceVal = distance.value
    // console.log(distanceVal)
    // 满足偏移的条件
    const diff =
      distanceVal > 0 && distanceVal < TITLE_HEIGHT
        ? distanceVal - TITLE_HEIGHT
        : 0
    // 利用js动态动画原理
    return { transform: `translate3d(0, ${diff}px, 0)` }
  })
  // 获取的数据发生变化时候保证能正确获取高度
  watch(
    () => props.data,
    async () => {
      // 等待一个nextTick后数据才在视图上
      await nextTick()
      calculate()
    }
  )
  // 监听滚动条的位置并获取当前区域位置索引(保证让字母在头上)
  watch(scrollY, (newY) => {
    const listHeightsVal = listHeights
    for (let i = 0; i < listHeightsVal.length - 1; i++) {
      const heightTop = listHeightsVal[i]
      const heightBottom = listHeightsVal[i + 1]
      if (newY >= heightTop && newY <= heightBottom) {
        currentIndex.value = i
        // 他是一个个区间段来的
        distance.value = heightBottom - newY
      }
    }
  })
  // 计算列表高度(具体算法)
  function calculate() {
    // 获取当前节点的孩子节点列表
    const list = groupRef.value.children
    const listHeightsVal = listHeights
    let height = 0
    // 初始化数组
    listHeightsVal.length = 0
    listHeightsVal.push(height)
    // 计算每个高度并叠加
    for (let i = 0; i < list.length; i++) {
      // 获取每个孩子的高度并叠加
      height += list[i].offsetHeight
      listHeightsVal.push(height)
    }
  }

  function onScroll(pos) {
    scrollY.value = -pos.y
  }
  return { groupRef, onScroll, fixedTitle, finedStyle, currentIndex }
}
